<script setup>
import { onMounted, ref, computed } from 'vue';
import { useToast } from "primevue/usetoast";
import { jwtDecode } from "jwt-decode";
import axios from '../../util/interceptor';

const name = ref("");
const id = ref("");
const job = ref("");
const phone = ref("");
const email = ref("");
const brief = ref("");
const userImgUrl = ref("");
const toast = useToast();
const password1 = ref("");
const password2 = ref("");
const password3 = ref("");
const differentPassword = ref(false)
const displayConfirmation = ref(false);
const PasswordDialog = ref(false);
const invalidUsername = ref(false);

onMounted(() => {
    init();
    getUserInfo();
});

const init = async () => {
    const token = localStorage.getItem("token");
    const decoded = jwtDecode(token);
    console.log(decoded);
    const userInfo = await axios.get(`/user/getUsers/${decoded.id}`);
    console.log(userInfo.data);
    const jobInfo = await axios.get(`/dept/getDept/${userInfo.data.data.deptId}`);
    console.log(jobInfo.data);
    id.value = decoded.id
    name.value = userInfo.data.data.username;
    phone.value = userInfo.data.data.phone;
    email.value = userInfo.data.data.email;
    brief.value = userInfo.data.data.brief;
    job.value = jobInfo.data.data.name;
    userImgUrl.value = userInfo.data.data.imgUrl;
};

const getUserInfo = async () => {


};

const close = () => {
    displayConfirmation.value = false;
};

const alterProfile = async () => {
    displayConfirmation.value = false;
    if (name.value == "") {
        invalidUsername.value = true;
        toast.add({ severity: 'warn', summary: 'Failed', detail: "用户名不能为空", life: 3000 });
        return;
    }
    const profileData = ref({
        name: name.value,
        email: email.value,
        phone: phone.value,
        brief: brief.value,
        id: id.value
    });
    console.log(profileData.value);
    const response = await axios.post("/user/updateProfile", profileData.value)
    console.log(response);
    if (response.data.code == 200) {
        toast.add({ severity: 'success', summary: 'Attention', detail: response.data.message, life: 3000 });
        setTimeout(() => {
            location.reload();
        }, 1500);
    }
    else {
        toast.add({ severity: 'warn', summary: 'Failed', detail: "头像上传失败", life: 3000 });
    }
}

const confirmButton = () => {
    displayConfirmation.value = true;
}

const showPasswordDg = () => {
    PasswordDialog.value = true;
    password1.value = "";
    password2.value = "";
    password3.value = "";
}

const hideDialog = () => {
    PasswordDialog.value = false;
}

const changePassword = () => {
    console.log(!password2.value)
    if (!password2.value || !password3.value) {
        differentPassword.value = true;
        return;
    } else if (password2.value != password3.value) {
        toast.add({ severity: 'error', summary: 'Error', detail: "密码输入不一致", life: 3000 });
        return;
    }
    const token = localStorage.getItem("token");
    const decoded = jwtDecode(token);
    console.log(decoded.username)
    const response = axios.post(`/user/login/${decoded.username}/${password1.value}`)
    if(response.data.code == 200){
        console.log(success);
    }
}

const upload = (event) => {
    console.log(event)
    if (event.xhr.status == 200) {
        toast.add({ severity: 'info', summary: 'Success', detail: "头像上传成功", life: 3000 });
        setTimeout(() => {
            location.reload();
        }, 2000);
    }
};

const userImg = computed(() => {
    return `${name.value}`
});

const dropdownItems = ref([
    { name: 'Option 1', code: 'Option 1' },
    { name: 'Option 2', code: 'Option 2' },
    { name: 'Option 3', code: 'Option 3' }
]);

const dropdownItem = ref(null);
</script>

<template>
    <div class="grid">
        <div class="col-12">
            <div class="card">
                <h5>基本信息</h5>
                <div class="p-fluid formgrid grid">
                    <div class="field col-12 md:col-1">
                        <label>&emsp;</label>
                        <img :src="userImgUrl" alt="Image" height="50" width="50" class="mb-3"
                            style="border-radius: 50px" />
                        <Toast />
                    </div>
                    <div class="field col-12 md:col-5">
                        <lable></lable>
                        <FileUpload :name="userImg" url="/api/userImage" @upload="upload($event)"
                            :multiple="false" accept="image/*" :maxFileSize="1000000" chooseLabel="添加" uploadLabel="上传"
                            cancelLabel="取消" fileLimit="1">
                            <template #empty>
                                <p>拖拽或添加文件上传头像</p>
                            </template>
                        </FileUpload>
                        <!-- <FileUpload name="shitwork[]" url="/api/image" @upload="onAdvancedUpload($event)"
                            :multiple="false" accept="image/*" :maxFileSize="1000000">
                            <template #empty>
                                <p>Drag and drop files to here to upload.</p>
                            </template>
                        </FileUpload> -->
                    </div>
                    <div class="field col-12 md:col-6">
                        <label for="firstname2">用户名</label>
                        <InputText :class="[{ 'p-invalid': invalidUsername }]" id="firstname2" type="text" v-model="name" />
                        <div>
                            &nbsp;
                        </div>
                        <label for="lastname2">职位</label>
                        <InputText id="lastname2" type="text" v-model="job" disabled />
                    </div>
                </div>
            </div>
        </div>

        <div class="col-12">
            <div class="card">
                <h5>详细信息</h5>
                <div class="p-fluid formgrid grid">
                    <div class="field col-12 md:col-6">
                        <label for="firstname2">手机号</label>
                        <InputMask id="basic" v-model="phone" mask="999-9999-9999" placeholder="000-0000-0000" />
                    </div>
                    <div class="field col-12 md:col-6">
                        <label for="lastname2">邮箱</label>
                        <InputText id="lastname2" type="text" v-model="email" />
                    </div>
                    <div class="field col-12">
                        <label for="address">介绍</label>
                        <Textarea id="address" rows="4" v-model="brief" placeholder="还什么都没有" />
                    </div>
                </div>
                <Toast />
                <div class="p-fluid formgrid grid">
                    <div class="field col-12 md:col-2">
                        <Button label="更新信息" @Click="confirmButton()"></Button>
                    </div>
                    <div class="field col-12 md:col-2">
                        <Button icon="pi pi-external-link" label="更改密码" @Click="showPasswordDg()"></Button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <Dialog header="提示" v-model:visible="displayConfirmation" :style="{ width: '350px' }" :modal="true">
        <div class="flex align-items-center justify-content-center">
            <i class="pi pi-exclamation-triangle mr-3" style="font-size: 2rem" />
            <span>确认更改信息？</span>
        </div>
        <template #footer>
            <Button label="No" icon="pi pi-times" @click="close" class="p-button-text" />
            <Button label="Yes" icon="pi pi-check" @click="alterProfile" class="p-button-text" autofocus />
        </template>
    </Dialog>

    <Dialog v-model:visible="PasswordDialog" :style="{ width: '450px' }" header="修改密码：" :modal="true" class="p-fluid">
        <div class="field">
            <label for="oldPassword">现用密码：</label>
            <Password id="password1" v-model="password1" placeholder="Password" :toggleMask="true"
                :class="[`w-full mb-3`, { 'p-invalid': invalidPassword }]" inputClass="w-full"
                :inputStyle="{ padding: '1rem' }" :feedback="false" @blur="validatePassword"></Password>
            <label for="oldPassword">新密码：</label>
            <Password id="password1" v-model="password2" :toggleMask="true"
                :class="[`w-full mb-3`, { 'p-invalid': differentPassword }]" inputClass="w-full"
                :inputStyle="{ padding: '1rem' }" :feedback="false" @blur="validatePassword"></Password>
            <label for="oldPassword">确认密码：</label>
            <Password id="password1" v-model="password3" :toggleMask="true"
                :class="[`w-full mb-3`, { 'p-invalid': differentPassword }]" inputClass="w-full"
                :inputStyle="{ padding: '1rem' }" :feedback="false" @blur="validatePassword"></Password>
        </div>
        <!-- <div class="field">
                <label for="name">部门名称</label>
                <InputText id="name" v-model.trim="product.deptName" required="true" autofocus
                    :class="{ 'p-invalid': submitted && !product.deptName }" />
                <small class="p-error" v-if="submitted && !product.deptName">Name is required.</small>
            </div>
            <div class="field">
                <label class="mb-3">Category</label>
                <div class="formgrid grid">
                    <div class="field-radiobutton col-6" v-for="category of menus" :key="category.id">
                        <Checkbox v-model="product.menuIds" :inputId="category.id" name="category" :value="category.id" />
                        <label :for="category.id">{{ category.menuName }}</label>
                    </div>
                </div>
                <small class="p-error" v-if="submitted && !product.menuIds">Name is required.</small>
            </div> -->
        <template #footer>
            <Button label="取消" icon="pi pi-times" text @click="hideDialog" />
            <Button label="修改" icon="pi pi-check" text @click="changePassword" />
        </template>
    </Dialog>
</template>
